package org.jdesktop.swingx.table.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.swing.table.TableModel;

import org.jdesktop.swingx.table.model.calc.I_Calc;
import org.jdesktop.swingx.table.model.tran.I_Transition;

public class GroupTableModelWapper extends AbstractCompositionTableModelWapper {

	int groupIndex;
	Map<Integer,I_Calc> defCalc;
	I_Transition defTran;
	
	public GroupTableModelWapper(TableModel t,int groupIndex,I_Transition tran,Map<Integer,I_Calc> defCalc) {
		super(t);
		this.groupIndex=groupIndex;
		this.defCalc=defCalc;
		this.defTran=tran;
	}

	@Override
	public void analysis(TableModel base,ArrayList<AbstractTableModelWapper> subModel) {
        Map<Object,List<Integer>> group=new HashMap<Object,List<Integer>>();
        Object colValue;
		for(int i=0;i<base.getRowCount();i++){
			colValue=base.getValueAt(i, groupIndex);
			if(defTran!=null)
				colValue=defTran.trans(colValue);
			if(group.containsKey(colValue)){
				group.get(colValue).add(i);
			}else{
				List<Integer> intList=new ArrayList<Integer>();
				intList.add(i);
				group.put(colValue, intList);
			}
		}
		
		Iterator<List<Integer>> it=group.values().iterator();
		
		while(it.hasNext()){
			List<Integer> val=it.next();
			int[] rows=new int[val.size()];
			for(int i=0;i<val.size();i++)
				rows[i]=val.get(i);
			AbstractTableModelWapper wapModel=new RowSectionTableModelWapper(base,rows);
			if(defCalc!=null)
				wapModel=new CalcRowTableModelWapper(wapModel,defCalc);
			subModel.add(wapModel);
		}
	}
}
